package controllers

import (
	"github.com/go-errors/errors"
	"github.com/revel/revel"
	"io/ioutil"
	"time"
)

type Controller struct {
	*revel.Controller
	t    time.Time
	body []byte
}

var ErrMap map[string]map[int]string

func (c *Controller) RenderError(errCode int, err error) revel.Result {
	if value, ok := err.(*errors.Error); ok {
		revel.ERROR.Println(value.ErrorStack())
	} else {
		revel.ERROR.Println(err)
	}

	return c.RenderJson(ErrResult{ErrCode: errCode,
		ErrMsg: ErrMap[c.Request.Locale][errCode]})
}

func (c *Controller) RenderErrorCode(errCode int) revel.Result {
	return c.RenderJson(ErrResult{ErrCode: errCode,
		ErrMsg: ErrMap[c.Request.Locale][errCode]})
}

func (c *Controller) RenderResult(obj interface{}) revel.Result {
	return c.RenderJson(obj)
}

func (c *Controller) StartAction() revel.Result {
	defer c.Request.Body.Close()
	c.body, _ = ioutil.ReadAll(c.Request.Body)
	c.t = time.Now()

	revel.INFO.Printf("Start %s request:%s from:%s",
		c.Request.RequestURI, c.body, c.Request.RemoteAddr)
	return nil
}

func (c *Controller) EndAction() revel.Result {
	revel.INFO.Printf("End %s respose:%+v used:%v",
		c.Request.RequestURI, c.Result, time.Since(c.t))
	return nil
}

func init() {
	revel.InterceptMethod((*Controller).StartAction, revel.BEFORE)
	revel.InterceptMethod((*Controller).EndAction, revel.AFTER)
}

type ErrResult struct {
	ErrCode int    `json:"errCode"`
	ErrMsg  string `json:"errMsg"`
}
